const {
	Service
} = require("uni-cloud-router");
const {
	result_success,
	result_error
} = require('http-result-modle');
const db = uniCloud.database();
const $ = db.command.aggregate;
const uidObj = require('uni-id');
module.exports = class LocalStockService extends(
	Service
) {

	async getNum(event) {
		let uid = '';
		if (this.ctx.event.uniIdToken) {
			// 已登录，获取当前登录 uid
			const userRes = await uidObj.checkToken(this.ctx.event.uniIdToken);
			if (userRes.code == 0) {
				uid = userRes.uid;
			}
		}
		if (!uid) {
			response.msg = '当前未登录'
			return response;
		}
		const localStockNumRes = await db.collection('wmzmall-local-stock').aggregate()
			.match({
				create_uid: $.eq(uid)
			})
			.group({
				_id: null,
				num: $.sum('$goods_num')
			})
			.end();
		let inventory = 0
		if (localStockNumRes.data[0] && localStockNumRes.data[0].num) {
			inventory = localStockNumRes.data[0].num
		}
		const memberRes = await this.db.collection('wmzmall-member').doc(uid)
			.field({
				local_th_total: true,
				local_xh_total: true
			}).get();
		return result_success({
			inventory: inventory,
			local_th_total: memberRes.data[0].local_th_total,
			local_xh_total: memberRes.data[0].local_xh_total
		});
	}
	async getData(event) {
		let uid = '';
		if (this.ctx.event.uniIdToken) {
			// 已登录，获取当前登录 uid
			const userRes = await uidObj.checkToken(this.ctx.event.uniIdToken);
			if (userRes.code == 0) {
				uid = userRes.uid;
			}
		}
		if (!uid) {
			response.msg = '当前未登录'
			return response;
		}
		const localStockListRes = await this.db.collection('wmzmall-local-stock').where({
			create_uid: uid
		}).get()
		return result_success(localStockListRes.data);
	}
	async getStockLogs(event) {
		let uid = '';
		if (this.ctx.event.uniIdToken) {
			// 已登录，获取当前登录 uid
			const userRes = await uidObj.checkToken(this.ctx.event.uniIdToken);
			if (userRes.code == 0) {
				uid = userRes.uid;
			}
		}
		if (!uid) {
			response.msg = '当前未登录'
			return response;
		}
		const localStockListRes = await this.db.collection('wmzmall-local-stock-logs').where({
			create_uid: uid,
			type: 0
		}).orderBy('create_time', 'desc').get()
		return result_success(localStockListRes.data);
	}
	async getSales(event) {
		let uid = '';
		if (this.ctx.event.uniIdToken) {
			// 已登录，获取当前登录 uid
			const userRes = await uidObj.checkToken(this.ctx.event.uniIdToken);
			if (userRes.code == 0) {
				uid = userRes.uid;
			}
		}
		if (!uid) {
			response.msg = '当前未登录'
			return response;
		}
		/* const cloudStockListRes = await this.db.collection('wmzmall-cloud-stock-logs').where({
			create_uid: uid,
			type: 0
		}).orderBy('create_time', 'desc').get() */
		return result_success([]);
	}
};